package club.ljwang.controller;

import club.ljwang.entity.Result;
import club.ljwang.pojo.Menu2;
import club.ljwang.pojo.Role;
import club.ljwang.service.MenuService;
import club.ljwang.service.UserService;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Auther: wangl
 * @Date: 2020/3/7 21:02
 * @Description:
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Reference
    MenuService menuService;


    @Reference
    UserService userService;

    @RequestMapping("getUserName")
    public Result getUserName() {
        User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return new Result(true, "查询用户名成功", user.getUsername());
    }


    @RequestMapping("/getMenuList")
    public Result getMenuList(){
        try {
            Map map = new HashMap();
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            club.ljwang.pojo.User healthUser = userService.findByUserName(user.getUsername());
            Set<Role> roles = healthUser.getRoles();
            if(CollectionUtil.isNotEmpty(roles)){
                List<Integer> roleIds = new ArrayList<>();
                for (Role role : roles) {
                    roleIds.add(role.getId());
                }
                List<Menu2> menu2s = menuService.getMenuList(roleIds);
                map.put("menuList",menu2s);
            }
            map.put("username",user.getUsername());
            return new Result(true,"成功",map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"失败");
        }
    }
}
